<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 流式对话测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .chat-container {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 15px;
            margin-bottom: 20px;
            background: #fafafa;
        }
        .message {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
        }
        .user-message {
            background: #e3f2fd;
            text-align: right;
        }
        .ai-message {
            background: #f1f8e9;
        }
        .input-container {
            display: flex;
            gap: 10px;
        }
        #messageInput {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            background: #2196f3;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background: #1976d2;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .stop-button {
            background: #f44336;
        }
        .stop-button:hover {
            background: #d32f2f;
        }
        .status {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
        }
        .status.connected {
            background: #c8e6c9;
            color: #2e7d32;
        }
        .status.error {
            background: #ffcdd2;
            color: #c62828;
        }
        .typing-indicator {
            font-style: italic;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1>AI 流式对话测试</h1>
        
        <div id="status" class="status">准备就绪</div>
        
        <div class="chat-messages" id="chatMessages">
            <div class="message ai-message">
                <strong>AI:</strong> 你好！我是AI助手，有什么可以帮助你的吗？
            </div>
        </div>
        
        <div class="input-container">
            <input type="text" id="messageInput" placeholder="输入你的消息..." />
            <button id="sendButton" onclick="sendMessage()">发送</button>
            <button id="stopButton" onclick="stopGeneration()" style="display: none;" class="stop-button">停止生成</button>
        </div>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script>
        let socket = null;
        let currentAiMessage = '';
        let isStreaming = false;
        let currentConversationId = null;

        function updateStatus(message, type = '') {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
        }

        function addMessage(content, isUser = false) {
            const chatMessages = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
            messageDiv.innerHTML = `<strong>${isUser ? '用户' : 'AI'}:</strong> ${content}`;
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function addTypingIndicator() {
            const chatMessages = document.getElementById('chatMessages');
            const typingDiv = document.createElement('div');
            typingDiv.id = 'typingIndicator';
            typingDiv.className = 'message ai-message typing-indicator';
            typingDiv.innerHTML = '<strong>AI:</strong> 正在思考...';
            chatMessages.appendChild(typingDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function removeTypingIndicator() {
            const typingIndicator = document.getElementById('typingIndicator');
            if (typingIndicator) {
                typingIndicator.remove();
            }
        }

        function showStopButton() {
            document.getElementById('stopButton').style.display = 'inline-block';
        }

        function hideStopButton() {
            document.getElementById('stopButton').style.display = 'none';
        }

        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const sendButton = document.getElementById('sendButton');
            const message = messageInput.value.trim();
            
            if (!message || isStreaming) return;

            // 添加用户消息
            addMessage(message, true);
            messageInput.value = '';
            
            // 禁用输入
            sendButton.disabled = true;
            isStreaming = true;
            currentAiMessage = '';
            
            // 显示停止按钮
            showStopButton();
            
            // 添加打字指示器
            addTypingIndicator();
            
            // 准备消息历史
            const messages = [
                { name: '用户', message: message }
            ];

            // 发送消息到服务器
            socket.emit('chat', {
                message: messages
            });
        }

        function stopGeneration() {
            if (currentConversationId && isStreaming) {
                console.log('Stopping generation for conversationId:', currentConversationId);
                socket.emit('stopGeneration', {
                    conversationId: currentConversationId
                });
            }
        }

        function resetUI() {
            const sendButton = document.getElementById('sendButton');
            sendButton.disabled = false;
            isStreaming = false;
            hideStopButton();
            removeTypingIndicator();
        }

        // 初始化WebSocket连接
        function initSocket() {
            socket = io();

            // 监听连接建立
            socket.on('connect', () => {
                updateStatus('WebSocket连接已建立', 'connected');
            });

            // 监听连接断开
            socket.on('disconnect', () => {
                updateStatus('WebSocket连接已断开', 'error');
                resetUI();
            });

            // 监听消息事件
            socket.on('message', (data) => {
                console.log('Received message:', data);
                if (data.type === 'connected') {
                    updateStatus('AI正在回复...', 'connected');
                    removeTypingIndicator();
                }
            });

            // 监听聊天内容
            socket.on('chatContent', (data) => {
                console.log('Received chat content:', data);
                currentConversationId = data.conversationId;
                currentAiMessage += data.content;
                removeTypingIndicator();
                
                // 更新或创建AI消息
                let aiMessageDiv = document.querySelector('.ai-message:last-child');
                if (!aiMessageDiv || aiMessageDiv.querySelector('.typing-indicator')) {
                    aiMessageDiv = document.createElement('div');
                    aiMessageDiv.className = 'message ai-message';
                    document.getElementById('chatMessages').appendChild(aiMessageDiv);
                }
                aiMessageDiv.innerHTML = `<strong>AI:</strong> ${currentAiMessage}`;
                document.getElementById('chatMessages').scrollTop = document.getElementById('chatMessages').scrollHeight;
            });

            // 监听聊天完成
            socket.on('chatDone', (data) => {
                console.log('Chat done:', data);
                updateStatus('对话完成', 'connected');
                resetUI();
            });

            // 监听聊天错误
            socket.on('chatError', (data) => {
                console.log('Chat error:', data);
                updateStatus(`错误: ${data.message}`, 'error');
                resetUI();
            });

            // 监听生成停止
            socket.on('generationStopped', (data) => {
                console.log('Generation stopped:', data);
                if (data.success) {
                    updateStatus('生成已中断', 'connected');
                    // 在AI消息后添加中断提示
                    const aiMessageDiv = document.querySelector('.ai-message:last-child');
                    if (aiMessageDiv) {
                        const stopDiv = document.createElement('div');
                        stopDiv.style.fontStyle = 'italic';
                        stopDiv.style.color = '#666';
                        stopDiv.textContent = '[生成已中断]';
                        aiMessageDiv.appendChild(stopDiv);
                    }
                } else {
                    updateStatus(`中断失败: ${data.message}`, 'error');
                }
                resetUI();
            });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initSocket();
        });

        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    </script>
</body>
</html>